package com.example.springbootjwt.controller;

import cn.hutool.jwt.JWT;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * JWT 操作：使用 hutool 框架提供 api
 * hutool 文档说明：https://hutool.cn/docs/#/jwt/%E6%A6%82%E8%BF%B0?id=%e4%bd%bf%e7%94%a8
 */
@RestController
@RequestMapping("/jwt")
public class JwtController {
    // JWT 私有秘钥
    private final String secretKey = "java666";

    @RequestMapping("/create")
    public String create(Long userid, String username) {
        if (userid == null || !StringUtils.hasLength(username)) {
            return "fail";
        }
        String token = JWT.create()
                .setPayload("userid", userid)
                .setPayload("username", username)
                .setKey(secretKey.getBytes())
                .sign();
        return token;
    }

    @RequestMapping("/get")
    public String decode(String token) {
        if (!StringUtils.hasLength(token)) {
            return "fail";
        }
        // JWT 验证
        boolean verify = JWT.of(token).setKey(secretKey.getBytes()).verify();
        if (verify) { // 验证成功
            JWT jwt = JWT.of(token);
            Long userid = Long.parseLong(jwt.getPayload("userid").toString());
            String username = jwt.getPayload("username").toString();
            String userinfo = "userid=" + userid +
                    " | username=" + username;
            System.out.println(userinfo);
            return userinfo;
        }
        return "fail";
    }
}
